//接收上传的excel文件，保存解析返回objects
const xlsx = require('xlsx');

async function getExcelObjs (f, t) {
    try {
        const workbook = xlsx.readFile(f);
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const thead = []
        Object.keys(worksheet).forEach(key => {
            const val = /(\d+(\.\d+)?)/.exec(key)
            if (val && val[0] === '1') {
                thead.push(worksheet[key].v)
            }
        })
        let theadRule = []
        if (t === 'metadata') {
             theadRule = [
                 'System', 'Tissue', 'VirusTaxonomyID',
                 'SampleID', 'Gender', 'AgeGroup', 'Age',
                 'Country', 'Race', 'CollectionDate'
            ];
        } else if (t === 'metamapExpression') {
             theadRule = [
                 'System', 'Organ', 'VirusFamily',
                 'VirusName', 'VirusTaxonomy', 'Expression'
            ];
        } else {
             theadRule = [
                 'System', 'Organ', 'VirusFamily', 'VirusName', 'VirusTaxonomy',
                 'Evidence', 'Kingdom', 'Phylum', 'Class', 'Order', 'Family',
                 'Genus', 'Species', 'NucleicAcidType'
             ]
        }
        const isValid = thead.every(value => theadRule.includes(value));
        if(!isValid) {
            return {
                s: false,
                m: '上传的excel格式错误'
            };
        } else {
            const data = xlsx.utils.sheet_to_json(worksheet)
            return {
                s: true,
                m: data
            }
        }
    } catch (err) {
        return {
            s: false,
            m: err.message
        }
    }
}
module.exports = getExcelObjs
